#!/bin/bash
set -uo pipefail

#==============================================================#
# File      :   pgbouncer-create-db
# Mtime     :   2020-09-04
# Desc      :   add database to pgbouncer pool
# Path      :   /pg/bin/pgbouncer-create-db
# Copyright (C) 2018-2022 Ruohang Feng
#==============================================================#


#--------------------------------------------------------------#
# Name: pgbouncer-create-db
# Desc: Add or modify pgbouncer userlist
# Arg1: database name
# Arg2: connection string (optional)
# Note: Run this as dbsu (postgres)
#--------------------------------------------------------------#
function pgbouncer-create-db(){
	local database=$1
	local connstr=${2-'host=/var/run/postgresql'}
	local dblist=${3-'/etc/pgbouncer/database.txt'}

	mkdir -p /etc/pgbouncer/
	touch ${dblist}
	if grep -q ${database} ${dblist}; then
		sed -i "/${database}[[:blank:]]*=.*$/d" ${dblist}
	fi
	echo "${database} = ${connstr}" >> ${dblist}
}

pgbouncer-create-db $@
